﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using System.Data;
using System.IO;

namespace LDSP.UI.EnterpriseAdmin
{
    public partial class AddFavorateCodification : BRL.BaseEnterpriseAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    this.CheckQS();
                }
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitDataSelect();
                    }
                    this.InitDataDynamicAfter();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected string TitleName = "法律法规";
        protected string ReferenceName = "发布文号";
        protected string SummaryName = "法规概述";
        protected string PrincipalName = "责任人";
        protected string KeyItemsName = "关键条款";
        protected string CommentName = "备注";
        protected string Display = "";
        protected string ImplementLabel = "";
        protected string SelfEvaluationLabel = "";

        protected Codification m_codification = null;
        protected Catalog m_catalog = null;
        protected R_EnterpriseCodification m_favorite = null;

        /// <summary>
        /// 源文档的类型
        /// </summary>
        protected DocType DocType
        {
            get { return (DocType)this.GetVSInt("DocType"); }
            set
            {
                this.SetVS("DocType", value);
            }
        }
        protected string OriginalIds
        {
            get { return this.GetVSString("OriginalIds"); }
            set
            {
                this.SetVS("OriginalIds", value);
            }
        }
        protected int CatalogID
        {
            get { return this.GetVSInt("CatalogID"); }
            set
            {
                this.SetVS("CatalogID", value);
                m_catalog = null;
            }
        }
        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_codification = null;
                m_favorite = null;
            }
        }
        protected Codification Codification
        {
            get
            {
                if (m_codification == null)
                {
                    m_codification = new Codification();
                    if (LastID != 0)
                    {
                        m_codification.GetProperties(LastID);
                    }
                }
                return m_codification;
            }
        }
        protected Catalog Catalog
        {
            get
            {
                if (m_catalog == null)
                {
                    m_catalog = new Catalog();
                    if (CatalogID != 0)
                    {
                        m_catalog.GetProperties(CatalogID);
                    }
                }
                return m_catalog;
            }
        }
        protected R_EnterpriseCodification Favorite
        {
            get
            {
                if (m_favorite == null)
                {
                    m_favorite = new R_EnterpriseCodification().GetPropertiesByEnterpriseAndCodification(LoginUser.EnterpriseID, Codification.ID);
                }
                return m_favorite;
            }
        }
        protected bool IsAdd
        {
            get { return LastID == 0; }
        }

        protected void CheckQS()
        {
            CatalogID = this.GetInt(this.Request.QueryString["cid"]);
            if (Catalog.ID == 0)
            {
                CatalogID = 0;
            }
            LastID = this.GetInt(this.Request.QueryString["id"]);
            DocType = (DocType)this.GetInt(this.Request.QueryString["docType"]);
            if (Codification.ID == 0)
            {
                LastID = 0;
            }
            else
            {
                CatalogID = Codification.CatalogID;
                DocType = Codification.DocType;
            }
        }
        protected bool RB()
        {
            bool res = true;
            if (IsAdd)
            {
                if (CatalogID == 0)
                {
                    this.JSAlert("请选择栏目后添加！");
                    res = false;
                }
                else if (Catalog.EnterpriseID != LoginUser.EnterpriseID
                    && !HaveCatalogPermission(CatalogID))
                {
                    this.JSAlert("您没有被授权该栏目！");
                    res = false;
                }
            }
            else if (!IsAdd && Codification.EnterpriseID != LoginUser.EnterpriseID)
            {
                if (Favorite.ID == 0)
                {
                    this.JSAlert(string.Format("请选择正确的{0}进行修改！", DocType.ToString()));
                    res = false;
                }
            }
            if (!res)
            {
                this.JSCloseWindow();
            }
            return res;
        }
        protected void SetStatus()
        {
            this.lbl_op.Text = IsAdd ? "【添加】" : "【修改】";
            this.lbl_op.Style["color"] = IsAdd ? "red" : "blue";
            this.ClientComfirm(this.btn_ok, string.Format("您确定执行{0}操作吗？", IsAdd ? "添加" : "修改"));

            bool enable = IsAdd || Codification.EnterpriseID > 0;
            this.txt_name.Enabled = enable;
            this.txt_organization.Enabled = enable;
            this.txt_invalidList.Enabled = enable;
            this.txt_implementDT.Enabled = enable;
            this.txt_referenceNumber.Enabled = enable;
            this.ddl_category.Enabled = enable;
            this.btn_getInvalidList.Enabled = enable;
            this.chb_isValid.Enabled = enable;
            this.txt_releaseDT.Enabled = enable;
            this.fup_file.Enabled = enable;
        }
        protected void InitDataSelect()
        {
            this.JSShowModalDialog(string.Format("id={0}", LastID), this.btn_getInvalidList);
            this.txt_name.Text = Codification.Name;

            this.lbl_catalog.Text = IsAdd ? Catalog.Name : Codification.Catalog.Name;
            this.txt_organization.Text = Codification.Organization;
            this.txt_referenceNumber.Text = Codification.ReferenceNumber;
            this.txt_implementDT.Text = this.FormatDT(Codification.ImplementDT);
            this.txt_releaseDT.Text = this.FormatDT(Codification.ReleaseDT);
            this.chb_isValid.Checked = Codification.IsValid;
            this.hlk_file.Text = "";
            if (Codification.FileName != "")
            {
                this.hlk_file.Text = Codification.FileName;
                this.hlk_file.NavigateUrl = this.GetDownloadJSString(Codification);
            }

            this.txt_summary.Text = Favorite.Name;
            this.txt_keyItems.Text = Favorite.KeyItems;
            this.txt_action.Text = Favorite.Action;
            this.txt_principal.Text = Favorite.Principal;
            this.txt_selfEvaluation.Text = Favorite.SelfEvaluation;
            this.txt_comment.Text = Favorite.Comment;

            this.BindDDLCategory();
            this.BindDDLPriority();
            this.InitInvalidList();
            this.SetStatus();
        }
        protected void InitDataDynamicBefore()
        {
            if (DocType == BRL.DocType.标准)
            {
                this.Display = "display:none";
                this.TitleName = "标准";
                this.ReferenceName = "标准号";
                this.SummaryName = "标准概述";
            }
            this.ImplementLabel = this.LoginUser.Enterprise.EnterpriseConfig.ActionFieldName;
            this.SelfEvaluationLabel = this.LoginUser.Enterprise.EnterpriseConfig.SelfEvaluationFieldName;
        }
        protected void InitDataDynamicAfter()
        {
            this.JSSetDateTimeReadOnly(this.txt_implementDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_releaseDT.ClientID);
        }

        protected void BindDDLCategory()
        {
            DataTable dt = new Category().GetRecordsByDocType(DocType);
            this.ddl_category.Items.Clear();
            this.ddl_category.Items.Add(new ListItem("--请选择类别--", "0"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.ddl_category.Items.Add(new ListItem(dt.Rows[i]["name"].ToString(), dt.Rows[i]["id"].ToString()));
            }
            try
            {
                this.ddl_category.SelectedIndex = 0;
                this.ddl_category.SelectedValue = Codification.CategoryID.ToString();
            }
            catch { }
        }
        protected void BindDDLPriority()
        {
            this.ddl_priority.Items.Clear();
            this.ddl_priority.Items.Add(new ListItem(Priority.低.ToString(), ((int)Priority.低).ToString()));
            this.ddl_priority.Items.Add(new ListItem(Priority.中.ToString(), ((int)Priority.中).ToString()));
            this.ddl_priority.Items.Add(new ListItem(Priority.高.ToString(), ((int)Priority.高).ToString()));
            try
            {
                this.ddl_priority.SelectedIndex = 1;
                this.ddl_priority.SelectedValue = ((int)Favorite.Priority).ToString();
            }
            catch { }

        }
        protected void InitInvalidList()
        {
            List<R_DisableDoc> invalidList = new R_DisableDoc().GetListBySource(LastID);
            List<string> list = new List<string>();
            for (int i = 0; i < invalidList.Count; i++)
            {
                list.Add(invalidList[i].DestinationID.ToString());
            }
            this.OriginalIds = this.CombineStrS(list);
            this.InvalidList(PageID, OriginalIds);
            this.ShowInvalidList();
        }

        protected bool CompareInvalidListModification()
        {
            List<string> oldList = this.SplitStrS(this.OriginalIds);
            List<string> newList = this.SplitStrS(this.InvalidList(PageID));
            if (oldList.Count != newList.Count)
            {
                return true;
            }
            for (int i = 0; i < newList.Count; i++)
            {
                bool find = false;
                for (int j = 0; j < oldList.Count; j++)
                {
                    if (newList[i] == oldList[j])
                    {
                        find = true;
                        oldList.RemoveAt(j);
                        j--;
                        break;
                    }
                }
                if (!find)
                {
                    return true;
                }
            }
            return false;
        }
        protected void CreateDisableRelationship()
        {
            List<string> list = this.SplitStrS(this.InvalidList(PageID));
            for (int i = 0; i < list.Count; i++)
            {
                int id = this.GetInt(list[i]);
                if (id > 0)
                {
                    R_DisableDoc ett = new R_DisableDoc();
                    ett.SourceID = Codification.ID;
                    ett.DestinationID = id;
                    if (ett.Destination.DocType != Codification.DocType
                        || ett.Destination.EnterpriseID != LoginUser.EnterpriseID
                        || ett.SourceID == ett.DestinationID)
                    {
                        continue;
                    }
                    ett.Add();
                }
            }
        }

        protected void ShowInvalidList()
        {
            List<string> idList = this.SplitStrS(this.InvalidList(PageID));
            List<string> nameList = new List<string>();
            for (int i = 0; i < idList.Count; i++)
            {
                int id = this.GetInt(idList[i]);
                Codification ett = new Codification();
                ett.GetProperties(id);
                nameList.Add(ett.Name);
            }
            this.txt_invalidList.Text = this.CombineStrS(nameList);
        }

        protected void ValidateDataBefore()
        {
        }
        protected void ValidateDataAfter()
        {
            if (Codification.Name == "")
            {
                throw new BYFW.BOL.CustomException("名称不能为空！");
            }
        }
        protected void SetData()
        {
            this.ValidateDataBefore();
            if (IsAdd || Codification.EnterpriseID > 0)
            {
                Codification.Name = this.txt_name.Text.Trim();
                Codification.Comment = this.txt_comment.Text;
                Codification.ReleaseDT = DateTime.Parse(this.txt_releaseDT.Text.Trim());
                Codification.ImplementDT = DateTime.Parse(this.txt_implementDT.Text.Trim());
                Codification.CategoryID = this.GetInt(this.ddl_category.SelectedValue);
                Codification.Organization = this.txt_organization.Text.Trim();
                Codification.ReferenceNumber = this.txt_referenceNumber.Text.Trim();
                Codification.IsValid = this.chb_isValid.Checked;
                Codification.Summary = this.txt_summary.Text;
                Codification.KeyItems = this.txt_keyItems.Text;
                Codification.Action = this.txt_action.Text;
                if (IsAdd)
                {
                    Codification.DocType = DocType;
                    Codification.EnterpriseID = LoginUser.EnterpriseID;
                    Codification.CatalogID = CatalogID;
                }
                if (this.fup_file.HasFile)
                {
                    this.UploadFileIsvalid();
                    Codification.CreateNewFile(this.fup_file.FileName);
                    this.fup_file.SaveAs(Codification.GetDownloadFileFullName());
                    Codification.UploadDT = DateTime.Parse(DateTime.Now.ToShortDateString());
                }
            }
            if (Favorite.ID == 0)
            {
                Favorite.FavoriteDT = DateTime.Now;
                Favorite.EnterpriseID = LoginUser.EnterpriseID;
            }
            Favorite.Comment = this.txt_comment.Text;
            Favorite.Principal = this.txt_principal.Text;
            Favorite.Priority = (Priority)this.GetInt(this.ddl_priority.SelectedValue);
            Favorite.Name = this.txt_summary.Text;
            Favorite.KeyItems = this.txt_keyItems.Text;
            Favorite.Action = this.txt_action.Text;
            Favorite.SelfEvaluation = this.txt_selfEvaluation.Text;

            this.ValidateDataAfter();
        }
        protected void Add()
        {
            this.SetData();
            Codification.Add();
            this.CreateDisableRelationship();
            Favorite.DocID = Codification.ID;
            Favorite.Add();
            this.LastID = 0;
            this.JSAlert("添加成功！");
        }
        protected void Update()
        {
            string tmpName = Codification.Name;
            bool tmpValid = Codification.IsValid;
            DateTime tmpImplementDT = Codification.ImplementDT;

            this.SetData();

            if (tmpValid != Codification.IsValid
                || tmpImplementDT != Codification.ImplementDT)
            {
                new R_DisableDoc().UpdateBySourceAndDestination(Codification.ID);
            }
            if (Codification.EnterpriseID > 0 && this.CompareInvalidListModification())
            {
                new R_DisableDoc().DeleteBySource(null, Codification.ID);
                this.CreateDisableRelationship();
            }
            Codification.Update();

            if (Favorite.ID == 0)
            {
                Favorite.DocID = Codification.ID;
                Favorite.Add();
            }
            else
            {
                Favorite.Update();
            }
            this.JSAlert("更新成功！");
        }

        private void JSShowModalDialog(string arg, WebControl ctrl)
        {
            this.JSShowDialog(string.Format("ChooseInvalidList.aspx?PageID={0}&docType={1}&{2}", PageID, (int)DocType, arg), 1200, 800, ctrl, null, null, null, null, null, null, null, true, null, null, null, null, null);
        }

        protected void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                this.LastID = 0;
                this.InitDataSelect();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsAdd)
                {
                    this.Add();
                }
                else
                {
                    this.Update();
                }
                this.InitDataSelect();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void btn_getInvalidList_Click(object sender, EventArgs e)
        {
            this.ShowInvalidList();
        }
    }

}